# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : HTTP流式请求示例.py
# @Author: dongguangwen
# @Date  : 2025-03-22 11:12
import requests


url = "https://spark-api-open.xf-yun.com/v1/chat/completions"
data = {
    "model": "generalv3.5",  # 指定请求的模型
    "messages": [
        {
            "role": "user",
            "content": "你是谁"
        }
    ],
    "stream": True
}
header = {
    "Authorization": "Bearer 123456"  # 注意此处把“123456”替换为自己的APIPassword
}
response = requests.post(url, headers=header, json=data, stream=True)

# 流式响应解析示例
response.encoding = "utf-8"
for line in response.iter_lines(decode_unicode="utf-8"):
    print(line)

"""
data: {"code":0,"message":"Success","sid":"cha000be829@dx195bbd7b6aeb894532","id":"cha000be829@dx195bbd7b6aeb894532","created":1742613231,"choices":[{"delta":{"role":"assistant","content":"您好，我是科大讯"},"index":0}]}

data: {"code":0,"message":"Success","sid":"cha000be829@dx195bbd7b6aeb894532","id":"cha000be829@dx195bbd7b6aeb894532","created":1742613231,"choices":[{"delta":{"role":"assistant","content":"飞研发的认知智能"},"index":0}]}

data: {"code":0,"message":"Success","sid":"cha000be829@dx195bbd7b6aeb894532","id":"cha000be829@dx195bbd7b6aeb894532","created":1742613231,"choices":[{"delta":{"role":"assistant","content":"大模型，我的名字"},"index":0}]}

data: {"code":0,"message":"Success","sid":"cha000be829@dx195bbd7b6aeb894532","id":"cha000be829@dx195bbd7b6aeb894532","created":1742613232,"choices":[{"delta":{"role":"assistant","content":"叫讯飞星火认知大"},"index":0}]}

data: {"code":0,"message":"Success","sid":"cha000be829@dx195bbd7b6aeb894532","id":"cha000be829@dx195bbd7b6aeb894532","created":1742613232,"choices":[{"delta":{"role":"assistant","content":"模型。我可以和人"},"index":0}]}

data: {"code":0,"message":"Success","sid":"cha000be829@dx195bbd7b6aeb894532","id":"cha000be829@dx195bbd7b6aeb894532","created":1742613232,"choices":[{"delta":{"role":"assistant","content":"类进行自然交流，"},"index":0}]}

data: {"code":0,"message":"Success","sid":"cha000be829@dx195bbd7b6aeb894532","id":"cha000be829@dx195bbd7b6aeb894532","created":1742613232,"choices":[{"delta":{"role":"assistant","content":"解答问题，高效完"},"index":0}]}

data: {"code":0,"message":"Success","sid":"cha000be829@dx195bbd7b6aeb894532","id":"cha000be829@dx195bbd7b6aeb894532","created":1742613232,"choices":[{"delta":{"role":"assistant","content":"成各领域认知智能"},"index":0}]}

data: {"code":0,"message":"Success","sid":"cha000be829@dx195bbd7b6aeb894532","id":"cha000be829@dx195bbd7b6aeb894532","created":1742613232,"choices":[{"delta":{"role":"assistant","content":"需求。"},"index":0}]}

data: {"code":0,"message":"Success","sid":"cha000be829@dx195bbd7b6aeb894532","id":"cha000be829@dx195bbd7b6aeb894532","created":1742613232,"choices":[{"delta":{"role":"assistant"},"index":0}],"usage":{"prompt_tokens":2,"completion_tokens":40,"total_tokens":42}}

data: [DONE]
"""